package info.maxhis.bn.birthday;

import info.maxhis.bn.MainActivity;
import info.maxhis.bn.R;
import info.maxhis.bn.sms.SMSListActivity;
import info.maxhis.entity.Friend;
import info.maxhis.service.FriendService;
import info.maxhis.util.CalendarUtil;
import info.maxhis.util.SharedData;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

/**
 * 显示所有生日列表
 * 
 * @author iStar
 * 
 */
public class BirthdayListActivity extends ListActivity {
	private List<Map<String, Object>> data;
	private FriendListAdapter adapter;
	private FriendService fs;
	private SharedData share;
	private Context context;
	private Resources rs;
	private Intent it;
	private ProgressDialog progressDialog = null;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_birthday_list);
		progressDialog = ProgressDialog.show(context, "请稍候", "正在加载好友列表...");
		it = getIntent();
		rs = getResources();
		fs = new FriendService(this);
		share = new SharedData(context);
//		setTitle(R.string.title_birthday_list);

		prepareData();

	}

	/**
	 * 发短信菜单监听器
	 * 
	 * @author iStar
	 * 
	 */
	private class SMSMenuListener implements OnMenuItemClickListener {

		@Override
		public boolean onMenuItemClick(MenuItem item) {
			Friend f = fs.findFriendById(share.getFriendId());
			String phone = f.getPhone();
			// 调转到短信选择页面
			Intent intent = new Intent(context, SMSListActivity.class);
			intent.putExtra("forSend", true);
			intent.putExtra("phone", phone);
			startActivity(intent);
			BirthdayListActivity.this.finish();
			return false;
		}

	}

	/**
	 * 打电话菜单监听器
	 * 
	 * @author iStar
	 * 
	 */
	private class DialMenuListener implements OnMenuItemClickListener {

		@Override
		public boolean onMenuItemClick(MenuItem item) {
			Friend f = fs.findFriendById(share.getFriendId());
			String phone = f.getPhone();
			Intent intent = new Intent("android.intent.action.CALL",
					Uri.parse("tel:" + phone));
			context.startActivity(intent);
			BirthdayListActivity.this.finish();
			return false;
		}
	}

	private class EditMenuListener implements OnMenuItemClickListener {

		@Override
		public boolean onMenuItemClick(MenuItem item) {
			Intent intent = new Intent(context, EditBirthdayActivity.class);
			startActivity(intent);
			finish();
			return false;
		}
		
	}
	
	/**
	 * 删除菜单监听器
	 * 
	 * @author iStar
	 * 
	 */
	private class DeleteMenuListener implements OnMenuItemClickListener {

		@Override
		public boolean onMenuItemClick(MenuItem item) {
			final Friend f = fs.findFriendById(share.getFriendId());
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			// e.g. 确定删除张三的生日提醒信息吗？
			String msg = rs.getString(R.string.delete_before_name)
					+ f.getName() + rs.getString(R.string.delete_after_name);
			builder.setMessage(msg)
					.setIcon(R.drawable.ask)
					.setTitle(rs.getString(R.string.notice))
					.setPositiveButton(R.string.confern,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									fs.removeFriend(f);
									Intent intent = new Intent(context,
											BirthdayListActivity.class);
									startActivity(intent);
									finish();
								}
							}).setNegativeButton(R.string.cancel, null);
			AlertDialog alert = builder.create();
			alert.show();
			return false;
		}

	}

	/**
	 * 长按列表监听器
	 * 
	 * @author iStar
	 * 
	 */
	private class FriendLongClickListener implements OnItemLongClickListener {

		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View view,
				int position, long id) {
			TextView idView = (TextView) view.findViewById(R.id.friend_id);
			String fid = idView.getText().toString();
			share.saveFriendId(fid);
			return false;
		}
	}

	/**
	 * 获取数据
	 */
	private void prepareData() {
		new Thread() {
			public void run() {
				ArrayList<Friend> friends = null;
				String from = it.getStringExtra("from");
				String to = it.getStringExtra("to");
				String name = it.getStringExtra("name");
				if (from != null && to != null) {
					friends = fs.getFriends(from, to);
				} else if (name != null) {
					friends = fs.findFriendByName(name);
				} else {
					friends = fs.getAllFriends();
				}
				data = new ArrayList<Map<String, Object>>();
				if (friends != null) {
					Collections.sort(friends); // 按生日排序
					for (Friend f : friends) {
						Map<String, Object> item = new HashMap<String, Object>();
						String dir = Environment.getExternalStorageDirectory()+"/birthday/head";
			        	File file = new File(dir, f.getUid() + ".jpg");
			        	
			        	Bitmap bm;
			        	if (file.exists()) {
			        		bm = BitmapFactory.decodeFile(file.getAbsolutePath());
						} else {
							bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.profile_default);
						}
			        	item.put("profile", bm);
						item.put("name", f.getName());
						item.put("birthday", CalendarUtil.formatBirthday(f));
						int leftDays = CalendarUtil.daysLeft2Birthday(f);
						item.put("leftdays",leftDays == 0 ? rs.getString(R.string.today) : leftDays + rs.getString(R.string.days_left));
						item.put("age", CalendarUtil.getAge(f));
						item.put("id", f.getId());
						data.add(item);
					}
				}

				Message msg = new Message();
				msg.what = 1;
				handler.sendEmptyMessage(1);
			};
		}.start();
	}

	// 关闭进度框
	private Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				
				adapter = new FriendListAdapter(data, context);
				setListAdapter(adapter);

				getListView().setTextFilterEnabled(true);
				getListView().setOnItemLongClickListener(
						new FriendLongClickListener());
				getListView().setOnCreateContextMenuListener(
						new View.OnCreateContextMenuListener() {

							@Override
							public void onCreateContextMenu(ContextMenu menu,
									View v, ContextMenuInfo menuInfo) {
								Friend f = fs.findFriendById(share
										.getFriendId());
								menu.setHeaderTitle(R.string.pls_select);
								// 编辑
								menu.add(R.string.edit).setOnMenuItemClickListener(new EditMenuListener());
								// 删除
								menu.add(R.string.delete)
										.setOnMenuItemClickListener(
												new DeleteMenuListener());
								// 发送短信
								menu.add(
										rs.getString(R.string.sms)
												+ f.getName())
										.setOnMenuItemClickListener(
												new SMSMenuListener());
								// 拨打电话
								menu.add(
										rs.getString(R.string.dial)
												+ f.getName() + "("
												+ f.getPhone() + ")")
										.setOnMenuItemClickListener(
												new DialMenuListener());
							}
						});

				onListViewEmpty();
				progressDialog.dismiss();
				break;

			default:
				break;
			}
		};
	};

	/**
	 * 当ListView为空时显示提示信息
	 */
	private void onListViewEmpty() {
		ListView listView = getListView();
		TextView tv = new TextView(this);
		tv.setText("无好友生日信息！");
		tv.setGravity(Gravity.CENTER);
		tv.setTextSize(25); // 设置字体大小

		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		addContentView(tv, params);
		listView.setEmptyView(tv);
	}
/*
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode ==  KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent(context, MainActivity.class);
			startActivity(intent);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}
	*/
}
